import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../building/buildinfo.dart';

class InheritedWidgetTestRoute extends StatefulWidget {
  @override
  _State createState() => new _State();
}

class _State extends State<InheritedWidgetTestRoute> {
  @override
  Widget build(BuildContext context) {
    var data = Provider.of<BuildInfo>(context);
//    var data = Provider.of<Map>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("Inherited方式传递数据"),
      ),
      body: Column(
        children: <Widget>[
          RaisedButton(
            child: Text("id=${data?.id},name=${data?.name}"),
//            child: Text(data?.name),
            textColor: Colors.blue,
            onPressed: () {
              data?.id = "1002";
              data?.name = "flutter2";
//              data?.setName("flutter2"); // 触发notifyListeners自动刷新所有子Widget
            },
          ),
          Container(
            alignment: Alignment.center,
            height: 40.0,
            child: Text("id=${data?.id},name=${data?.name}"),
//            child: Text(data?.id),
          ),
          IDataChildWidget(),
        ],
      ),
    );
  }

  /// 一般来说，子widget很少会重写此方法，因为在依赖改变后framework也都会调用build()方法。
  /// 但是，如果你需要在依赖改变后执行一些昂贵的操作，
  /// 比如网络请求，这时最好的方式就是在此方法中执行，这样可以避免每次build()都执行这些昂贵操作。
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    //父或祖先widget中的InheritedWidget改变(updateShouldNotify返回true)时会被调用。
    //如果build中没有依赖InheritedWidget，则此回调不会被调用。
    print("Dependencies change");
  }
}

class IDataChildWidget extends StatefulWidget {
  @override
  _IDataChildWidgetState createState() => _IDataChildWidgetState();
}

class _IDataChildWidgetState extends State<IDataChildWidget> {
  @override
  Widget build(BuildContext context) {
//    var data = Provider.of<Map>(context);
    final data = Provider.of<BuildInfo>(context);
    return Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            data?.id = "1002";
            data?.name = "flutter2";
            data?.notifyChanged();
          },
          child: Text("sub child id=${data?.id},name=${data?.name}"),
        )
      ],
    );
  }


}
